package com.df.barcodescaning.ui;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.df.barcodescaning.MyApplication;
import com.df.barcodescaning.R;
import com.df.barcodescaning.util.DialogUtils;
import com.df.barcodescaning.util.LoggerUtil;
import com.df.barcodescaning.util.MixSpeakUtil;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.df.barcodescaning.R.string.worker;
import static com.df.barcodescaning.instance.ReceivingInstances.ACTION_DF_SCAN_RESULT;
import static com.df.barcodescaning.instance.ReceivingInstances.ACTION_DF_SCAN_START_TO_APP;
import static com.df.barcodescaning.instance.ReceivingInstances.ACTION_DF_SCAN_STOP_TO_APP;
import static com.df.barcodescaning.instance.ReceivingInstances.RESULT;

public class ScaningActivity extends BaseActivity {

    private static final String TAG = "--Main--";

    public static final String SCANACT_KEY_ID = "ScaningActivity_id";
    public static final String SCANACT_KEY_TAG = "ScaningActivity_tag";

    private LinearLayout llRst;
    private MyReceiver mReceiver;
    private String code_id, code_tag;

    private MixSpeakUtil mixSpeakUtil;
    //创建震动服务对象
    private Vibrator mVibrator;
    private boolean isWindowFocus;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scaning);

        setTitle(getString(worker) + " " + MyApplication.getInstance().getLoggedUser().getUserName());

        mReceiver = new MyReceiver();

        Intent intent = getIntent();
        code_id = intent.getStringExtra(SCANACT_KEY_ID);
        code_tag = intent.getStringExtra(SCANACT_KEY_TAG);

        llRst = (LinearLayout) findViewById(R.id.ll_result);
        ((TextView)findViewById(R.id.tv_preset_id)).setText(code_id);
        ((TextView)findViewById(R.id.tv_code_tag)).setText(code_tag);

        new Thread(new Runnable() {
            @Override
            public void run() {

                String userName = MyApplication.getInstance().getLoggedUser().getUserName();
                DateFormat df = new SimpleDateFormat("yyyyMMdd");
                String logFileName = userName + "_扫描料号" + df.format(new Date())+".csv";
                LoggerUtil.setLogFileName(logFileName);
                //获取手机震动服务
                mVibrator=(Vibrator)getSystemService(Service.VIBRATOR_SERVICE);
                mixSpeakUtil= MixSpeakUtil.getInstance(ScaningActivity.this);
            }
        }).start();
    }

    @Override
    protected void onResume() {
        super.onResume();

        Intent sendIntent = new Intent(ACTION_DF_SCAN_START_TO_APP);
        sendBroadcast(sendIntent);

        IntentFilter ItFilter = new IntentFilter();
        ItFilter.addAction(ACTION_DF_SCAN_RESULT);
        registerReceiver(mReceiver, ItFilter);
    }

    @Override
    protected void onPause() {
        Intent sendIntent = new Intent(ACTION_DF_SCAN_STOP_TO_APP);
        sendBroadcast(sendIntent);

        unregisterReceiver(mReceiver);
        super.onPause();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        isWindowFocus = hasFocus;
    }

    @Override
    public void onBackPressed() {
        finish();
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void handleScanResult(String result) {
        String logStr ;
        String dialogTittle;
        String dialogMsg;
//            Toast.makeText(this, tvTittle.getText().toString() + " || " + result, Toast.LENGTH_SHORT).show();
        ((TextView)findViewById(R.id.tv_scan_rst)).setText(result);
        if(code_id.equals(result)) {  //扫描成功, 条码匹配正确
            llRst.setBackground(getResources().getDrawable(R.drawable.bg_box_correct));
            logStr = result + "," + getString(R.string.rst_scan_match);
//            dialogTittle = getString(R.string.rst_scan_match);    //modified: 只有扫描失败时才弹窗. 2018/6/5
//            MyApplication.getInstance().mixSpeakUtil.speak(getString(R.string.voice_alert_match));
            if (mixSpeakUtil != null) {
                mixSpeakUtil.speak(getString(R.string.voice_alert_match));
            }
        } else {    //条码不匹配,请确认
//            MyApplication.getInstance().mixSpeakUtil.speak(getString(R.string.voice_alert_mismatch));
            if (mixSpeakUtil != null) {
                mixSpeakUtil.speak(getString(R.string.voice_alert_mismatch));
            }
            llRst.setBackground(getResources().getDrawable(R.drawable.bg_box_err));
            logStr = result + "," + getString(R.string.rst_scan_mismatch);
            dialogTittle = getString(R.string.rst_scan_mismatch);
//            MyApplication.getInstance().mVibrator.vibrate(new long[]{100,100,100,1000},-1);
            mVibrator.vibrate(new long[]{100,100,100,1000},-1);
            dialogMsg = getString(R.string.rst_scan) + result;
            new DialogUtils(this, dialogTittle).hintDialog(dialogMsg, android.R.string.ok, null);
        }
        LoggerUtil.writeToDownloadDir(code_id + "," + logStr);
    }

    private class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (!isWindowFocus) return;
            if (intent.getAction().equalsIgnoreCase(ACTION_DF_SCAN_RESULT)) {
                String code = intent.getStringExtra(RESULT);
                code = code.trim();
                handleScanResult(code);
            }
        }
    };
}
